import config from '@/config/index';
import store from "@/store/store";

/**
 * 格式化金额显示，添加千分位
 * @param {String} value 金额字符串
 */
export function formatPrice(value) {
    if (!value) {
        return '';
    }
    return (value + '').replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

/**
 * 解析含有千分位的金额
 * @param {String} value 金额字符串
 */
export function parsePrice(value) {
    const valueStr = (value + '').replace(/(,*)/g, '');
    let valueNumber = parseMaxNumber(valueStr);
    return valueNumber;
}

/**
 * 限制数字大小
 * @param {String} value 金额字符串
 */
export function parseMaxNumber(valueStr, max = 999999999) {
    let valueNumber = parseFloat(valueStr);
    if (isNaN(valueNumber)) {
        return null;
    }
    let resValue;
    if (valueNumber > max) {
        resValue = max;
    } else {
        resValue = valueStr;
    }
    return resValue;
}


/**
 * 导出文件
 * @param {*} param 
 * @param {string} param.url 导出地址url
 * @param {string} param.method 导出类型 get || post
 * @param {Object} param.data 参数
 */
export function orderExport(param) {
    const { data, url } = param;
    let method = param.method || 'get';
    method = method.toLowerCase();
    let realUrl = '';
    if (url.indexOf('http')  > -1) {
        realUrl = url;
    } else {
        realUrl = url.indexOf('/') > -1 ? `${config.apiRoot}${url}` : `${config.apiRoot}/${url}`;
    }
    if (method === 'get') {
        let dataStr = `?Authorization=${store.state.token}`;
        let key;
        for( key in data) {
            if (data[key] && data[key] !== 'null') {
                dataStr += `&${key}=${data[key]}`;
            }
        }
        console.log(`${realUrl}${dataStr}`);
        window.open(`${realUrl}${dataStr}`);
    }
}